import {defineStore} from "pinia";
import {computed, ref} from "vue";
import {useUserStore} from "@/stores/userStore.js";
import {insertCartListAPI, findNewCartListAPI, delCartAPI} from "@/apis/cart.js";

export  const useCartStore = defineStore('cart',() => {

    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token )

    /**
     *  获取/更新购物车
     * @returns {Promise<void>}
     */
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }

    /**
     * 添加到购物车
     * @param goods
     */
    const addCart = async (goods) => {
        const { skuId, count } = goods
        // 判断是否登录
        if (isLogin.value) {
            await insertCartListAPI({ skuId, count })
            await updateNewList()
        } else {
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            // 判断购物车中是否已存在商品
            if (item) {
                item.count++
            } else {
                cartList.value.push(goods)
            }
        }

    }

    /**
     * 删除购物车
     * @param skuId
     */
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            updateNewList()
        } else {
            const idx = cartList.value.findIndex( (item) => skuId === item.skuId)
            cartList.value.splice(idx,1)
        }

    }
    /**
     * 清空购物车
     */
    const clearCart = () => {
        cartList.value = []
    }
    const totalCount = computed( () => cartList.value.reduce((a,c) => a + c.count,0)
    )
    const totalPrice = computed( () => cartList.value.reduce((a,c) => a + c.count * c.price,0)
    )

    /**
     * 购物车单选
     * @param skuId
     * @param selected
     */
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }

    /**
     * 购物车全选
     * @param selected
     */
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }
    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    // 已选商品数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a,c) => a + c.count,0))
    // 已选商品总价格
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a,c) => a + c.count * c.price,0))

    return {
        cartList,
        addCart,
        delCart,
        totalCount,
        totalPrice,
        singleCheck,
        allCheck,
        isAll,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }
},{
    persist:true,
})